package main

import (
	"context"
	"fmt"
	"gitee.com/DonHz/electronic-business-systems/mxshop_srvs/inventory_srv/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"sync"
)

var (
	invClient proto.InventoryClient
	conn      *grpc.ClientConn
	wg        sync.WaitGroup
)

func Init() {
	var err error
	conn, err = grpc.NewClient("127.0.0.1:58046", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		panic("create client connect failed: " + err.Error())
	}
	invClient = proto.NewInventoryClient(conn)
}

func main() {
	Init()
	defer conn.Close()
	wg.Add(40)
	//TestSetInv(421, 100)
	for i := 0; i < 40; i++ {
		go TestSell(&wg)
	}
	wg.Wait()
	//TestSetInv(421, 100)
	//TestInvDetail(421)
	//TestSell()
	//TestReBack()
}

func TestSetInv(goodsId, num int64) {
	_, err := invClient.SetInv(context.Background(), &proto.GoodsInvInfo{
		GoodsId: goodsId,
		Num:     num,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println("设置库存成功")
}

func TestInvDetail(goodsId int64) {
	resp, err := invClient.InvDetail(context.Background(), &proto.GoodsInvInfo{
		GoodsId: goodsId,
	})
	if err != nil {
		panic(err)
	}
	fmt.Println(resp.Num)
}

func TestSell(wg *sync.WaitGroup) {
	defer wg.Done()
	_, err := invClient.Sell(context.Background(), &proto.SellInfo{
		GoodsInfo: []*proto.GoodsInvInfo{
			{GoodsId: 421, Num: 1},
		},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println("库存扣减成功")

}

func TestReBack() {
	_, err := invClient.Reback(context.Background(), &proto.SellInfo{
		GoodsInfo: []*proto.GoodsInvInfo{
			{GoodsId: 421, Num: 1},
		},
	})
	if err != nil {
		panic(err)
	}
	fmt.Println("归还成功")
}
